package minimum;

import projectcvip.*;

/**
 *
 * @author Michał
 */
public class MinimumSupervisor extends JSBasic
{
    private int a;
    private int b;
    private int lengthPerTask;

    public MinimumSupervisor(int a, int b, int lengthPerTask)
    {
        this.a = a;
        this.b = b;
        this.lengthPerTask = lengthPerTask;
    }

    public void supervisor()
    {
        try
        {
            System.out.println("Nadzorca zaczyna prace.");
            int count = 0;
            Task task = new Task();
            for (int i = a; i <= b; i += lengthPerTask)
            {
                task.a = new Integer(i);
                int tmp = (i + lengthPerTask <= b) ? (i + lengthPerTask) : b;
                task.b = new Integer(tmp);
                System.out.println("Nadzorca zleca: a = " + task.a + "; b = " + task.b + ";");
                space.write(task, null, defaultLease);
                count++;
            }

            int min = Integer.MAX_VALUE;
            int x = 0;
            Result result = new Result();
            for (int i = 0; i < count; i++)
            {
                result.minY = null;
                result.x = null;
                System.out.println("Nadzorca pobiera odpowiedz...");
                result = (Result) space.take(result, null, defaultLease);
                if (result.minY < min)
                {
                    min = result.minY.intValue();
                    x = result.x.intValue();
                }
            }

            System.out.println("Minimum dla f(" + x + ") = " + min);
            task.a = null;
            task.b = null;
            space.write(task, null, defaultLease); //trujaca pigulka
        }
        catch (Exception ex)
        {
            System.out.println(ex);
        }
    }

    public void run()
    {
        supervisor();
    }
}
